import axios from 'axios'
import qs from 'qs'
import { isFormData } from '@/util'

import { Message } from 'element-ui'

const request = axios.create({
    baseURL: '',
    timeout: 60000,
    responseType: 'json',
})

// 请求拦截器
request.interceptors.request.use(
    config => {
		config.headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
		if(config.data.token !== null) config.headers['accessToken'] = localStorage.getItem('access_token')
		config.data = (!isFormData(config.data)) ? qs.stringify(config.data) : config.data;
        return config
    },
    error=> {
        Message.error('请求出错')
        return Promise.reject(error)
    })

// 响应拦截器
request.interceptors.response.use(
    response=> {
        if (response.status === 200) {
            if(response.data.statusCode == '400001' || response.data.statusCode == '400002'){
				Message.error('登录超时，请重新登录');
				localStorage.removeItem('access_token');
				location.reload();
			}
            return response.data
        } else {
            Message.error(response.statusText || '系统错误')
            return Promise.reject(response)
        }
    }, error=> {
        Message.error(error.message || '请求失败')
        return Promise.reject(error)
    })

export default request
